<template>
  <base-scroll :options="scrollOptions" ref="scroll">
    <div class="rank" ref="container">
      <rank-menu title="榜单推荐" :rank="rank.recommend" />
      <rank-official title="官方榜" :rank="rank.official" />
      <rank-menu title="特色榜" :rank="rank.special" />
      <rank-menu title="全球榜" :rank="rank.global" />
      <rank-menu title="地区榜" :rank="rank.region" />
      <rank-menu title="曲风榜" :rank="rank.style" />
      <rank-menu title="更多榜单" :rank="rank.other" />
    </div>
  </base-scroll>
</template>

<script>
import { mapGetters } from 'vuex'
import RankMenu from './components/RankMenu'
import RankOfficial from './components/RankOfficial'
import scrollMixin from '@/mixins/scroll'

export default {
  name: 'rank',
  mixins: [scrollMixin],
  components: {
    RankMenu,
    RankOfficial
  },
  data () {
    return {
      rank: {
        recommend: null,
        official: null,
        special: null,
        global: null,
        region: null,
        style: null,
        other: null
      }
    }
  },
  computed: {
    ...mapGetters(['cate'])
  },
  mounted () {
    this.initData()
  },
  methods: {
    initData () {
      // 读取缓存或重新请求数据
      if (!this.$storage.hasCache('toplist')) {
        console.log('In rank: 缓存失效，重新请求 toplist.')
        this.$api.getToplistDetail().then(res => {
          const { list } = res.data
          this.extractData(list)
          // 保存至 localStorage，有效时间为 10 分钟
          this.$storage.setItem('toplist', list, {
            ctime: Date.now(),
            maxAge: 10 * 60 * 1000
          })
        })
      } else {
        this.extractData(this.$storage.getItem('toplist').data)
      }
    },
    extractData (data) {
      // 提取数据，保存至 rank
      for (const key in this.rank) {
        // eslint-disable-next-line no-prototype-builtins
        if (this.rank.hasOwnProperty(key)) {
          this.rank[key] = data.filter(v => this.cate[key].includes(v.id))
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.rank {
  padding: 0 .1rem 0;
}
</style>
